import { useEffect, useState } from 'react';

import { useParams } from 'react-router-dom';

import { ArrowLeftOutlined } from '@ant-design/icons';

import { type ProjectDetail, deviceProjectDetailApi } from '@/api/projectManager';
import ExpandableDescriptions from '@/components/ExpandableCard/ExpandableDescriptions';

import { copyToClipboard, renderValue } from '@/utils';

/**
 * 项目详情页
 */
const ProjectDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { back } = useRouter();
  const [loading, setLoading] = useState(true);
  const [projectDetail, setProjectDetail] = useState<ProjectDetail | null>(null);

  // 获取项目详情
  const fetchProjectDetail = async () => {
    if (!id) return;

    try {
      setLoading(true);
      const res = await deviceProjectDetailApi({ id: Number(id) });
      if (res.success) {
        setProjectDetail(res.data as ProjectDetail);
      }
    } catch (error) {
      console.error('获取项目详情失败:', error);
      window.$message.error('获取项目详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProjectDetail();
  }, [id]);

  if (loading) {
    return (
      <div className="flex justify-center items-center h-96">
        <ASpin size="large" />
      </div>
    );
  }

  if (!projectDetail) {
    return (
      <div className="text-center py-8">
        <p>项目详情不存在</p>
        <AButton onClick={back}>返回项目列表</AButton>
      </div>
    );
  }

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <ArrowLeftOutlined className="mx-4" onClick={back} />
        <div className="page-main-title">项目详情</div>
        <div className="page-sub-title">查看项目的详细信息</div>
      </div>
      <div className="page-content-box">
        <div className="page-content">
          <ExpandableDescriptions
            title="基本信息"
            className="mb-6"
            defaultExpanded={false}
            basicItems={[
              <ADescriptions.Item key="name" label="项目名称">
                {renderValue(projectDetail.name)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="address" label="项目地址">
                {renderValue(projectDetail.address)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="authorizationCode" label="授权码">
                <div className="flex items-center">
                  {renderValue(projectDetail.authorizationCode)}
                  <AButton
                    type="link"
                    size="small"
                    className="ml-2"
                    onClick={() => {
                      copyToClipboard(projectDetail.authorizationCode || '');
                      window.$message.success('授权码已复制到剪贴板');
                    }}
                  >
                    复制
                  </AButton>
                </div>
              </ADescriptions.Item>,
              <ADescriptions.Item key="devices" label="绑定设备数量">
                {projectDetail.devices ? projectDetail.devices.length : 0} 台
              </ADescriptions.Item>,
            ]}
            expandedItems={[
              <ADescriptions.Item key="remark" label="项目描述" span={2}>
                {renderValue(projectDetail.remark)}
              </ADescriptions.Item>,
            ]}
          />

          {/* 绑定的设备列表 */}
          {projectDetail.devices && projectDetail.devices.length > 0 && (
            <ACard className="mt-6" title="绑定的设备">
              <ATable
                dataSource={projectDetail.devices}
                rowKey="id"
                pagination={false}
                columns={[
                  {
                    title: '设备名称',
                    dataIndex: 'deviceName',
                    key: 'deviceName',
                  },
                  {
                    title: '设备编码',
                    dataIndex: 'code',
                    key: 'code',
                  },
                  {
                    title: '所属产品',
                    dataIndex: 'productCode',
                    key: 'productCode',
                  },
                  {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (status: number) => {
                      const statusMap: Record<number, string> = {
                        0: '待激活',
                        1: '在线',
                        2: '离线',
                        3: '未知',
                      };
                      return statusMap[status] || '未知';
                    },
                  },
                ]}
              />
            </ACard>
          )}
        </div>
      </div>
    </div>
  );
};

export default ProjectDetailPage;
